/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huhu.contact.provider;

import com.huhu.contact.ResourceTable;
import com.huhu.contact.model.ContactBean;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.bundle.IBundleManager;
import ohos.utils.IntentConstants;
import ohos.utils.net.Uri;

import java.util.List;


/**
 * 单粘性Item适配器
 *
 * @since 2021-04-13
 */
public class StickyContactProvider extends BaseItemProvider {
    private Context context;
    private List<ContactBean> data;

    /**
     * Sticky滑动列表构造函数
     *
     * @param context    上下文
     * @param dataSource 数据源
     */
    public StickyContactProvider(Context context, List<ContactBean> dataSource) {
        this.context = context;
        this.data = dataSource;
    }

    public void setDataListChanged(List<ContactBean> dataSource) {
        this.data.clear();
        this.data = dataSource;
        notifyDataChanged();
    }

    @Override
    public int getCount() {
        return data != null ? data.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return data != null ? data.get(position) : null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
        ContactBean model = data.get(position);
        Component itemView = null;
        if (model.getType() == ContactBean.ITEM_TYPE.ITEM_TYPE_CHARACTER.ordinal()) {
            itemView = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_item_header, null, false);
            Text headerText = (Text) itemView.findComponentById(ResourceTable.Id_header_text);
            headerText.setText(model.getCharacter());
            headerText.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    new ToastDialog(context).setText(headerText.getText() + " clicked").show();
                }
            });
        } else {
            itemView = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_item_contact, null, false);
            Text itemText = (Text) itemView.findComponentById(ResourceTable.Id_item_text);
            itemText.setText(model.getName() + " " + model.getTelephone());
            Image call = (Image) itemView.findComponentById(ResourceTable.Id_call);
            Image message = (Image) itemView.findComponentById(ResourceTable.Id_message);
            call.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
//                    doCall(model.getTelephone());
                    doDial(model.getTelephone());
                }

            });
            message.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    doMessage(model.getTelephone());
                }
            });

        }
//        /**
//         * 动态修改字体颜色，必须在6位字体颜色值前+FF
//         * itemHolder.itemText.setTextColor(new Color(0xFF3F51B5));
//         */
//        if (position == 0 && itemView != null) {
//            itemView.setMarginTop(48);
//        }

        return itemView;
    }

    public List<ContactBean> getData() {
        return data;
    }

    /**
     * 跳转系统短信
     */
    private void doMessage(String telephone) {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
//                .withAction("android.intent.action.SENDTO") // Android写法 android.intent.action.SENDTO
                .withAction(IntentConstants.ACTION_SEND_SMS)
                .withUri(Uri.parse("smsto:" + telephone)) // 设置号码
                .withFlags(Intent.FLAG_NOT_OHOS_COMPONENT)
                .build();
        intent.setOperation(operation);
        context.startAbility(intent, 11);
    }

    /**
     * 申请拨打电话权限
     */
    private boolean requestPermissions() {
        if (context.verifySelfPermission("android.permission.CALL_PHONE") != IBundleManager.PERMISSION_GRANTED) {
            // 应用未被授予权限
            if (context.canRequestPermission("android.permission.CALL_PHONE")) {
                // 是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)
                context.requestPermissionsFromUser(new String[]{"android.permission.CALL_PHONE"}, 100);
            }
            return false;
        } else {
            // 权限已被授予
            return true;
        }
    }

    /**
     * 直接拨打电话
     * 需要申请权限
     */
    private void doCall(String destinationNum) {
        if (!requestPermissions()) {
            return;
        }
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withAction("android.intent.action.CALL") // 系统应用拨号盘
                .withUri(Uri.parse("tel:" + destinationNum)) // 设置号码
                .withFlags(2)
                .build();
        intent.setOperation(operation);
        // 启动Ability
        context.startAbility(intent, 10);

    }

    /**
     * 跳转系统拨打电话界面
     */
    private void doDial(String destinationNum) {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withAction(IntentConstants.ACTION_DIAL) // 系统应用拨号盘
//                .withBundleName(context.getCallingBundle()) // 应用拨号选择器
                .withUri(Uri.parse("tel:" + destinationNum)) // 设置号码
                .withFlags(2)
                .build();
        intent.setOperation(operation);
        // 启动Ability
        context.startAbility(intent, 10);

    }
}
